<template>
  <div class="call-dialog">
    <div class="call-dialog__main">
      <div class="call-dialog__current">
        <span class="call-dialog__sound">
          <img src="@/assets/icon/icon_hujiao_nor.svg" alt="" />
        </span>
        <div class="call-dialog__current-label">当前就诊</div>
        <div class="call-dialog__current-info" v-if="called">
          <span>{{
            useBaseDataStore.getEnumData(called?.visitPeriod, 'visitPeriodEnum')
          }}</span>
          · <span>{{ called?.visitSeqNo }}</span>
          <span>&nbsp;&nbsp;{{ called?.patientName || '暂无患者' }}</span>
        </div>
        <div class="call-dialog__current-info" v-else>
          <span>暂无患者</span>
        </div>
      </div>
      <div class="call-dialog__actions">
        <button
          class="call-btn"
          @click="onRepeatCall"
          :disabled="!called || !called.queueId"
        >
          重呼
        </button>
        <button
          class="call-btn"
          @click="onRepeatWait"
          :disabled="!called || !called.queueId"
        >
          过号
        </button>
      </div>
      <div class="call-dialog__next">
        <button
          class="call-btn call-btn-next"
          @click="next"
          :disabled="!WaitingList || WaitingList.length === 0"
        >
          下一位&nbsp;&nbsp;
          <span v-if="WaitingList && WaitingList.length > 0">
            {{ WaitingList[0]?.patientName || '暂无患者' }}
          </span>
        </button>
      </div>
    </div>
    <div class="call-dialog__table">
      <table>
        <thead>
          <tr>
            <th
              v-for="(tab, idx) in tabs"
              :key="tab.key"
              :class="{ 'tab-active': activeTab === tab.key }"
              @click="setTab(tab.key)"
            >
              {{ tab.label }}
            </th>
          </tr>
        </thead>
        <tbody v-if="callData.length > 0">
          <tr v-for="value in callData" :key="value.queueId">
            <td>
              {{
                useBaseDataStore.getEnumData(
                  value.visitPeriod,
                  'visitPeriodEnum'
                )
              }}{{ value.visitSeqNo }}号
            </td>
            <td>{{ value.patientName }}</td>
            <td :style="value.queueStatus == '5' ? 'color: red;' : ''">
              {{
                useBaseDataStore.getEnumData(
                  value.queueStatus,
                  'queueStatusEnum'
                )
              }}
              <span
                v-if="value.queueStatus == '5'"
                style="color: #18b3ab; margin-left: 10px; cursor: pointer"
                @click="onRepeatWait1(value)"
              >
                重新排队
              </span>
            </td>
            <!-- <td v-if="activeTab == 'wait'">候诊</td>
            <td v-else-if="activeTab == 'pending'">待诊</td>
            <td v-else-if="activeTab == 'done'">完诊</td> -->
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="3">
              <el-empty
                description="暂无数据"
                :image="emptyImage"
                :image-size="100"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import {
  getWaitingList,
  getToBeSeenList,
  getSeenList,
  callNext,
  repeatCall,
  postMissed,
  getCallingPatient,
  repeatWait
} from '@/api/medical';
import { ref, watch, onMounted } from 'vue';
import store from '@/store';
const useBaseDataStore = store.useBaseDataStore();
const tabs = ref([
  {
    key: 'wait',
    label: '候诊',
  },
  {
    key: 'pending',
    label: '待诊',
  },
  {
    key: 'done',
    label: '完诊',
  },
]);
const activeTab = ref('wait');
const callData = ref<any[]>([]);
const WaitingList = ref<any[]>([]);
const ToBeSeenList = ref<any[]>([]);
const SeenList = ref<any[]>([]);
const doctor = ref<any>({});
const called = ref<any>(null);
const emits = defineEmits(['refresh']);
const props = defineProps<{
  visitDate: any;
  visible: boolean;
}>();

watch(
  () => props.visible,
  async (val) => {
    if (!val) return;
    getWaitingList().then((res: any) => {
      WaitingList.value = res.data;
    });
    getCallingPatient().then((res: any) => {
      called.value = res.data;
    });
  },
  { immediate: true,deep: true }
);
const onRepeatWait1 = (data: any) => {
  repeatWait({queueId:data.queueId}).then((res: any) => {
    if (res.code == '200') {
      ElMessage.success('操作成功');
      setTab(activeTab.value);
    }else{
      //ElMessage.error(res.msg);
    }
  });
};
const setTab = (key: string) => {
  activeTab.value = key;

  if (key === 'wait') {
    getWaitingList().then((res: any) => {
      WaitingList.value = res.data;
      updateCallData();
    });
  } else if (key === 'pending') {
    getToBeSeenList().then((res: any) => {
      ToBeSeenList.value = res.data;
      updateCallData();
    });
  } else if (key === 'done') {
    getSeenList().then((res: any) => {
      SeenList.value = res.data;
      updateCallData();
    });
  }
};
// 根据当前激活 tab 或者第一个非空列表，更新 callData
const updateCallData = () => {
  let src: any[] = [];
  if (activeTab.value === 'wait') src = WaitingList.value || [];
  else if (activeTab.value === 'pending') src = ToBeSeenList.value || [];
  else if (activeTab.value === 'done') src = SeenList.value || [];

  callData.value = src;

  // 回退：选择第一个非空列表
};

// 监听三个列表与当前 tab，自动同步到 callData
watch(
  () => ({
    tab: activeTab.value,
    waitLen: WaitingList.value?.length || 0,
    pendLen: ToBeSeenList.value?.length || 0,
    doneLen: SeenList.value?.length || 0,
  }),
  () => updateCallData(),
  { immediate: true }
);
// 下一位
const next = async () => {
  if (WaitingList.value.length == 0) {
    ElMessage.warning('没有患者可叫');
    return;
  }
  const data = await callNext({ queueId: WaitingList.value[0].queueId });
  if (data.code == '200') {
    ElMessage.success('呼叫成功');

    emits('refresh');
    getCallingPatient().then((res: any) => {
      called.value = res.data;
    });
    getWaitingList().then((res: any) => {
      WaitingList.value = res.data;
      updateCallData();
    });
  } else {
    //ElMessage.error(data.msg);
  }
};
// 重新呼叫
const onRepeatCall = async () => {
  const data = await repeatCall({ queueId: called.value?.queueId });
  if (data.code == '200') {
    ElMessage.success('重新呼叫成功');
    getCallingPatient().then((res: any) => {
      called.value = res.data;
    });
    emits('refresh');
  } else {
    //ElMessage.error(data.msg);
  }
};
// 过号
const onRepeatWait = async () => {
  const data = await postMissed({ queueId: called.value?.queueId });
  if (data.code == '200') {
    ElMessage.success('过号成功');
    getCallingPatient().then((res: any) => {
      called.value = res.data;
    });
    getWaitingList().then((res: any) => {
      WaitingList.value = res.data;
      updateCallData();
      emits('refresh');
    });
  } else {
    //ElMessage.error(data.msg);
  }
};
onMounted(async () => {
  // setTab('wait');
});
</script>

<style scoped>
.call-dialog {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.13);
  font-family: inherit;
}
.call-dialog__title {
  font-size: 22px;
  font-weight: 600;
  color: #222;
  padding: 24px 0 0 28px;
  margin-bottom: 8px;
}
::v-deep(.modal-footer) {
  border: none !important;
}
.call-dialog__current {
  background: #e6f7f2;
  border-radius: 10px 10px 0 0;
  padding: 12px 0 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.call-dialog__sound {
  position: absolute;
  left: 16px;
  top: 12px;
  display: flex;
  align-items: center;
}
.call-dialog__current-label {
  color: #18b3ab;
  font-size: 15px;
  margin-bottom: 2px;
  margin-top: 2px;
}
.call-dialog__current-info {
  color: #18b3ab;
  font-size: 32px;
  font-weight: 600;
  letter-spacing: 2px;
  margin-bottom: 2px;
}
.call-dialog__actions {
  display: flex;
  width: 100%;
  background: #18b3ab;
  border-radius: 0 0 0 0;
}
.call-btn {
  flex: 1;
  background: transparent;
  border: none;
  color: #fff;
  font-size: 17px;
  font-weight: 500;
  padding: 10px 0;
  cursor: pointer;
  transition: background 0.2s;
}
.call-btn:not(:last-child) {
  border-right: 1px solid #fff;
}
.call-btn:active {
  background: #13a39a;
}
.call-dialog__next {
  margin-top: 12px;
  display: flex;
  justify-content: center;
}
.call-btn-next {
  width: 100%;
  background: #18b3ab;
  color: #fff;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  padding: 10px 0;
  border: none;
  margin: 0;
  cursor: pointer;
  transition: background 0.2s;
}
.call-btn-next:active {
  background: #13a39a;
}
.call-dialog__table {
  margin-top: 18px;
  border-radius: 10px;
  /* 固定高度，内容滚动 */
  height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
}
.call-dialog__table table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 15px;
  border: 1px solid #f0f0f0;
  border-bottom: none;
}
.call-dialog__table thead th {
  position: sticky;
  top: 0;
  z-index: 2; /* 盖住滚动内容 */
  /* 保证粘住时背景不透明 */
  background: #f5f7fa;
  box-shadow: 0 1px 0 #f0f0f0; /* 与下方边框衔接 */
}
.call-dialog__table th {
  background: #f5f7fa;
  color: #bbb;
  font-weight: 500;
  padding: 8px 0;
  text-align: center;
  width: 100px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.call-dialog__table th.tab-active {
  background: #fff;
  color: #000000;
  font-weight: 600;
  padding: 8px 0;
  box-shadow: 0 2px 8px rgba(24, 179, 171, 0.04);
  position: relative;
  z-index: 1;
}
.call-dialog__table td {
  background: #fff;
  color: #222;
  text-align: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}
</style>
